package com.codemes.happylist;

import javafx.application.Platform;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
import lombok.extern.slf4j.Slf4j;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.net.URL;

/**
 * @author nscoffee
 */
@Slf4j
public class CodemesToolTray {

    private static TrayIcon trayIcon;
    private static JMenuItem showItem;
    private static JMenuItem exitItem;
    private static ActionListener showListener;
    private static ActionListener exitListener;
    private static MouseAdapter mouseListener;
    private static JPopupMenu trayIconPopup;

    public static final String TRAY_ICON="/splash/trayIcon.jpg";

    public static void  initTray(Stage mainStage) throws AWTException {
        if (GraphicsEnvironment.isHeadless()||!SystemTray.isSupported()) {
            log.error("This environment does not support GUI operations.");
            log.error("不支持系统托盘>>{}",SystemTray.isSupported());
            return;
        }
        URL trayIconUrl = CodemesToolTray.class.getResource(TRAY_ICON);
        Image trayIconImage = Toolkit.getDefaultToolkit().getImage(trayIconUrl);
        trayIcon = new TrayIcon(trayIconImage);
        trayIcon.setImageAutoSize(true);
        //鼠标移到系统托盘,会显示提示文本
        trayIcon.setToolTip("乐事清单");

        try {
            SystemTray systemTray = SystemTray.getSystemTray();
            systemTray.add(trayIcon);
        } catch (AWTException e) {
            log.error("TrayIcon could not be added.");
        }
//        try {
            //UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
//            UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");
//        } catch (Exception e) {
//            e.printStackTrace();
//        }

        //如果使用Eclipse,需要右键Run as-选择Run Configuration,在第二栏Arguments选项中的VM Options中添加-Dfile.encoding=GBK
        showItem = new JMenuItem("打开主页面");
        //菜单项(退出)
        exitItem = new JMenuItem("退出程序");

        //弹出式菜单组件
        trayIconPopup = new JPopupMenu();
        trayIconPopup.add(showItem);
        trayIconPopup.addSeparator();
        trayIconPopup.add(exitItem);

        initlisten(mainStage);
    }
    /**
     * 更改系统托盘所监听的Stage
     */
    private static void initlisten(Stage mainStage){
        //防止报空指针异常
        if( showItem == null || exitItem == null || trayIcon == null){
            return;
        }
        //移除原来的事件
        showItem.removeActionListener(showListener);
        exitItem.removeActionListener(exitListener);
        trayIcon.removeMouseListener(mouseListener);
        //行为事件: 点击"打开"按钮,显示窗口
        showListener = e -> showStage(mainStage);
        //行为事件: 点击"退出"按钮, 就退出系统
        exitListener = e -> System.exit(0);
        //鼠标行为事件: 单机显示stage
        mouseListener = new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                trayIconPopup.setVisible(false);
                //鼠标左键
                if (e.getButton() == MouseEvent.BUTTON1) {
                    showStage(mainStage);
                }else if(e.getButton() == MouseEvent.BUTTON2){
                    log.info("点击中建..........");
                }else if(e.getButton() == MouseEvent.BUTTON3){
                    log.info("点击右键..打开菜单....");
                }
                if(SwingUtilities.isRightMouseButton(e)){
                    log.info("点击右键..打开菜单....SwingUtilities.isRightMouseButton....");
                    trayIconPopup.setLocation(e.getPoint());
                    trayIconPopup.setInvoker(trayIconPopup);
                    trayIconPopup.setVisible(true);
                }
            }
        };


        //给菜单项添加事件
        showItem.addActionListener(showListener);
        exitItem.addActionListener(exitListener);
        //给系统托盘添加鼠标响应事件
        trayIcon.addMouseListener(mouseListener);

        mainStage.setOnCloseRequest(event -> {
            log.info("窗口关闭事件>>>{}",event);
            hide(mainStage,event);
        });
    }

    /**
     * 关闭窗口
     */
    public static void hide(Stage mainStage, WindowEvent event){
        Platform.runLater(() -> {
            //如果支持系统托盘,就隐藏到托盘,不支持就直接退出
            if (SystemTray.isSupported()) {
                //stage.hide()与stage.close()等价
                mainStage.hide();
            } else {
                System.exit(0);
            }
        });
    }

    /**
     * 点击系统托盘,显示界面(并且显示在最前面,将最小化的状态设为false)
     */
    private static void showStage(Stage stage){
        log.info("点击系统托盘,显示界面>>>>>>>>>");
        Platform.runLater(() -> {
            //点击系统托盘,
            log.info("点击系统托盘,显示界面 判断显示状态>>>>>>>>>");
            if(stage.isIconified()){
                stage.setIconified(false);
            }
            log.info("show -{} focus-{} maxmine-{}",stage.isShowing(),stage.isFocused(),stage.isMaximized());
            if(!stage.isShowing()){
                stage.show();
                stage.toFront();
            } else if(stage.isShowing()){
                stage.hide();
            }
        });

    }
}
